//https://leetcode.cn/problems/island-perimeter/solutions/2876009/dao-yu-de-zhou-chang-c-by-xie-ding-e-de-unm9f/
#include <iostream>
#include <vector>

using namespace std;

class Solution {
public:
    int islandPerimeter(vector<vector<int>>& grid) {
        int n = grid.size(), m = grid[0].size();
        int result = 0;
        int dx[4] = {-1, 0, 1, 0}, dy[4] = {0, 1, 0, -1};

        for (int i = 0 ; i < n ; i ++ ) {
            for (int j = 0 ; j < m ; j ++ ) {
                if (grid[i][j] == 1) {
                    for (int k = 0 ;  k < 4 ; k ++ ) {
                        int nextx = i + dx[k];
                        int nexty = j + dy[k];
                        if (nextx < 0 || nextx >= n || nexty < 0 || nexty >= m
                                || grid[nextx][nexty] == 0) result ++;
                    }
                }
            }
        }
        return result;
    }
};